package com.mj.listen1._08_红黑树.tree;

import java.util.Comparator;

/**
 * 平衡二叉树
 */
public class BBST<E> extends BinarySearchTree<E> {
    public BBST() {

    }

    public BBST(Comparator<E> comparator) {
        super(comparator);
    }

    protected void rotate(
            Node<E> root,// 原来子树的根节点
            Node<E> a, Node<E> b, Node<E> c,
            Node<E> d,
            Node<E> e, Node<E> f, Node<E> g) {
        // 让d成为这颗子树的根节点
        d.parent = root.parent;
        if (root.isLeftChild()) {
            root.parent.left = d;
        } else if (root.isRightChild()) {
            root.parent.right = d;
        } else {
            // 是根节点
            root = d;
        }

        // a-b-c
        b.left = a;
        if (a != null) {
            a.parent = b;
        }
        b.right = c;
        if (c != null) {
            c.parent = b;
        }


        // e-f-g
        f.left = e;
        if (e != null) {
            e.parent = f;
        }
        f.right = g;
        if (g != null) {
            g.parent = f;
        }

        // b-d-f
        d.left = b;
        d.right = f;
        b.parent = d;
        f.parent = d;
    }

    // 左旋
    protected void rotateL(Node<E> grand) {
        Node<E> parent = grand.right;
        Node<E> child = parent.left;
        grand.right = child;
        parent.left = grand;
        afterRotate((Node<E>) grand, (Node<E>) parent, (Node<E>) child);
    }

    protected void afterRotate(Node<E> grand, Node<E> parent, Node<E> child) {
        // 让 parent 为子树的根节点
        parent.parent = grand.parent;
        // 将grand.parent的左或者右指针指向parent
        // 如果 grand 是其父节点的 left, 则将 grand.parent.left = parent;
        if (grand.isLeftChild()) {
            grand.parent.left = parent;
        } else if (grand.isRightChild()) {
            grand.parent.right = parent;
        } else {
            // 根节点
            root = parent;
        }

        // 更新 child 的 parent
        if (child != null) {
            child.parent = grand;
        }

        // 更新grand的parent
        grand.parent = parent;
    }

    // 右旋
    protected void rotateR(Node<E> grand) {
        Node<E> parent = grand.left;
        Node<E> child = parent.right;
        grand.left = child;
        parent.right = grand;

        // 让 parent 为子树的根节点
        afterRotate(grand, parent, child);
    }
}
